import { memo, useCallback, useEffect, useState } from "react";
import ReserveStyle from "./style";
import DataDisplay_content from "../../baseUI/dataDisplay_content/idnex";
import {
  useFetch_getCrouseInfo_simple,
  useGetCanReserveCourse,
} from "../../service/course";
import { useAsyncEffect } from "ahooks";
import { useGetOrgInfoSimple } from "../../service/organization";
import { ErrorBlock, Image, Popup, Steps } from "antd-mobile";
import { Step } from "antd-mobile/es/components/steps/step";
import CourseList from "./cpms/courseList";
import ReservePopup from "./cpms/reservePopup";

const Reserve = memo(() => {
  const [showPopup, setShowPopup] = useState(false);
  const [curClickCourseId, setCurClickCourseId] = useState<string>();
  const { getCanReserveCourse, loading } = useGetCanReserveCourse();
  const [canReserveCourses, setCanReserveCourses] = useState<
    {
      productId: string;
      courseId: string;
      orgId: string;
    }[]
  >();
  const [data, setData] = useState<
    {
      org: {
        id: string;
        name: string;
        logo: string;
      };
      course: {
        id: string;
        name: string;
        desc: string;
      }[];
    }[]
  >();
  const { getCourseInfo, loading: getCourseInfoLoading } =
    useFetch_getCrouseInfo_simple();
  const { getOrgInfoLazy, loading: getOrgInfoLazyLoading } =
    useGetOrgInfoSimple();
  useEffect(() => {
    void getCanReserveCourse().then((res) => {
      setCanReserveCourses(JSON.parse(res.data ?? "[]"));
    });
  }, []);
  useAsyncEffect(async () => {
    if (canReserveCourses) {
      const newData = [];
      for (const item of canReserveCourses) {
        const course = (await getCourseInfo(item.courseId)) as {
          id: string;
          name: string;
          desc: string;
        };
        // 同一机构不同课程
        const index = newData.findIndex((d) => d.org.id === item.orgId);
        if (index !== -1) {
          newData[index].course.push(course);
          break;
        }
        // 不同机构
        const org = (await getOrgInfoLazy(item.orgId)) as {
          id: string;
          name: string;
          logo: string;
        };
        newData.push({
          org: { ...org },
          course: [course],
        });
      }
      setData(newData);
    }
  }, [canReserveCourses]);

  const reserveBtnClick = useCallback((id: string) => {
    setShowPopup(true);
    setCurClickCourseId(id);
  }, []);
  const closePopupHandel = () => {
    setCurClickCourseId(undefined);
    setShowPopup(false);
  };
  return (
    <ReserveStyle>
      <DataDisplay_content
        loading={loading || getCourseInfoLoading || getOrgInfoLazyLoading}
        title="预约课程"
      >
        {!getCourseInfoLoading &&
        !getOrgInfoLazyLoading &&
        data?.length === 0 ? (
          <ErrorBlock
            status="empty"
            title="没有可以预约的课程"
            description="快去购买商品获取课程吧！"
          />
        ) : (
          <div className="reserve_content">
            <Steps direction="vertical">
              {data?.map((item) => (
                <Step
                  key={item.org.id}
                  title={"门店：" + item.org.name}
                  description={
                    <CourseList
                      data={item.course}
                      reserveBtnClick={(id: string) => reserveBtnClick(id)}
                    />
                  }
                  icon={
                    <Image
                      alt="门店logo加载失败"
                      src={item.org.logo}
                      fit="cover"
                    />
                  }
                />
              ))}
            </Steps>
          </div>
        )}
      </DataDisplay_content>
      <Popup
        visible={showPopup}
        onMaskClick={closePopupHandel}
        onClose={closePopupHandel}
      >
        <ReservePopup
          courseId={curClickCourseId}
          closePopup={closePopupHandel}
        />
      </Popup>
    </ReserveStyle>
  );
});

export default Reserve;
